#include "PatientListModel.h"

#include "PersonDatabase.h"

#include "UserDatabase.h"
#include "UserRelationDatabase.h"

PatientListModel::PatientListModel()
{

}

void PatientListModel::loadRelated(int userId)
{
    UserRelationDatabase relationDB;
    relationDB.loadRelatedUsers(userId);

    QList<int> * relatedIds = relationDB.getRelatedList();

    loadList(relatedIds);
}

void PatientListModel::loadAll()
{
    UserDatabase userDB;
    QList<int> * userIds = userDB.getUsersOfType(User::PATIENT);

    loadList(userIds);
}

void PatientListModel::loadList(QList<int> * list)
{
    patientItemList.clear();

    PersonDatabase personDB;

    for (int i = 0; i < list->size(); i++)
    {
        int id = list->at(i);
        PersonInfo info = personDB.getInfo(id);

        PatientListItem item;
        item.title = info.lastName + ", " + info.firstName;
        item.userId = id;

        patientItemList.push_back(item);
    }

    qSort(patientItemList.begin(), patientItemList.end(),
        [](const PatientListItem &p1, const PatientListItem &p2) -> bool {
            return p1.title < p2.title;
    });
}

int PatientListModel::rowCount(const QModelIndex &) const
{
    return patientItemList.size();
}

QVariant PatientListModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    if (index.row() >= patientItemList.size())
        return QVariant();

    if (role == Qt::DisplayRole)
    {
        return QVariant(patientItemList.at(index.row()).title);
    }
    else if (role == Qt::UserRole)
    {
        return QVariant(patientItemList.at(index.row()).userId);
    }
    else
        return QVariant();
}

QVariant PatientListModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role != Qt::DisplayRole)
        return QVariant();

    if (orientation == Qt::Horizontal)
        return QString("Column %1").arg(section);
    else
        return QString("Row %1").arg(section);
}

